<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class social extends CI_Controller {
	public function __construct(){
		parent::__construct();
		parse_str($_SERVER['QUERY_STRING'], $_REQUEST);
		$this->load->library('facebook');		
	}
	function index(){
		
		
	}
	function facebook(){
		if ($this->agent->is_referral() && !$this->session->userdata('game_referrer')){
			$this->session->set_userdata(array(
				'game_referrer'=>$this->agent->referrer(),
			));
		}
		if($this->facebook->check_login()){
			$fb_user = $this->facebook->get_user();
			$fb_id = $fb_user['id'];
			$f = $this->facebook->get_id_friends();
			$this->load->model("mfriend");
			$user = $this->muser->get($fb_id,'facebook_id');
			if($user){
				$this->muser->setLogin($user);
			}
			else if($user = $this->muser->get($fb_user['email'],'use_email')){
				$this->muser->update($user->use_id,'use_id',array('facebook_id'=>$fb_id));
				$this->mfriend->insert_fb_friends($user->use_id,$f);
				$this->muser->setLogin($user);
			}
			else {
				$arr_insert = array();
				$arr_insert['facebook_id'] = $fb_id;
				$arr_insert['use_email'] = $fb_user['email'];
				$arr_insert['use_account'] = $this->muser->parse_email($arr_insert['use_email']);
				$arr_insert['use_name'] = $fb_user['name'];
				$arr_insert['use_gender'] = (($fb_user['gender'] == 'male')?1:0);
				$use_account = $arr_insert['use_account'];
				for($i = 1; $i< 1000; $i++){
					$check = $this->muser->get($arr_insert['use_account'],'use_account');
					if($check){
						$arr_insert['use_account'] = $use_account.'.'.$i;
					}
					else {
						break;
					}
				}
				$arr_insert['use_avatar'] =  $this->muser->download_avatar($this->facebook->get_avatar(400,400),$arr_insert['use_account']);
				$arr_insert['use_password'] =  $this->muser->random_key(10);
				$user_id = $this->muser->registry($arr_insert);
				$arr_insert['use_id'] = $user_id ;
				$this->muser->setLogin($arr_insert);
				$this->mfriend->insert_fb_friends($user_id,$f);
			}
			 redirect(base_url().'redirect-facebook.html', 'refresh');
			
		}else {
			redirect($this->facebook->get_login_url(), 'refresh');
		}
	}
	
	function redirect() {
		$referer = $this->session->userdata('game_referrer');
		if ($referer) {
			$this->session->unset_userdata(array('game_referrer' => ''));
			redirect($referer,'refresh');
		}
		else {
			redirect(base_url(),'refresh');
		}
	}
	
	function check(){
		//$f = $this->facebook->get_friends();
		//$ref = (new FacebookRequest( $this->session, 'GET', '/me/'.$field ))->execute();
		$ret = $this->facebook->get_user_field('?fields=friends');
		/*
		$ret = $this->facebook->api(array(
		'method' => 'fql.query',
		'query' => "SELECT like_info FROM like WHERE object_id=678737885497009"
		 ));
		 */
		var_dump($ret);
	}
	
}
?>